package com.fortune.cat.convert;

import com.fortune.cat.bean.RouteDefinitionRecipient;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhaozeyang
 * @date 2019/4/18 16:13
 * @description
 */
public class RouteDefinitionConvert {

    public static RouteDefinition convertToRouteDefinition(RouteDefinitionRecipient recipient) {
        if (Objects.isNull(recipient)) {
            return null;
        }
        List<PredicateDefinition> predicates = recipient.getPredicates().stream().map(p -> {
            if (Objects.isNull(p)) {
                return null;
            }
            PredicateDefinition predicateDefinition = new PredicateDefinition();
            BeanUtils.copyProperties(p, predicateDefinition);
            return predicateDefinition;
        }).collect(Collectors.toList());
        List<FilterDefinition> filters = recipient.getFilters().stream().map(p -> {
            if (Objects.isNull(p)) {
                return null;
            }
            FilterDefinition filterDefinition = new FilterDefinition();
            BeanUtils.copyProperties(p, filterDefinition);
            return filterDefinition;
        }).collect(Collectors.toList());

        RouteDefinition routeDefinition = new RouteDefinition();
        BeanUtils.copyProperties(recipient, routeDefinition);
        routeDefinition.setFilters(filters);
        routeDefinition.setPredicates(predicates);
        routeDefinition.setId(recipient.getRouteId());
        return routeDefinition;
    }

    public static List<RouteDefinition> convertToRouteDefinition(List<RouteDefinitionRecipient> routeDefinitionRecipientList) {
        List<RouteDefinition> result = new ArrayList<>();
        routeDefinitionRecipientList.forEach(routeDefinitionRecipient -> result.add(convertToRouteDefinition(routeDefinitionRecipient)));
        return result;
    }
}
